package com.cyzy.educationalai.controller;

import com.cyzy.educationalai.chatMemory.RedisChatMemory;
import com.cyzy.educationalai.sercive.ChatService;
import lombok.RequiredArgsConstructor;
import org.springframework.ai.chat.client.ChatClient;
import org.springframework.ai.chat.memory.ChatMemory;
import org.springframework.ai.chat.messages.Message;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author zxw
 * @create 2025-05-17 下午4:37
 */
@RequiredArgsConstructor
@RestController
@RequestMapping("/ai")
public class ChatController {
    @Autowired
    private ChatClient chatClient;
    @Autowired
    private final RedisChatMemory redisChatMemory;
    @Autowired
    private ChatService chatService;


    //阻塞式聊天
    @RequestMapping("/chat")
    public String chat(@RequestParam("prompt") String prompt, @RequestParam("chatId") String chatId){
        List<String> course = chatService.getCourseDescriptions();
        String context = course.stream()
                .filter(desc -> desc != null && !desc.isEmpty())
                .collect(Collectors.joining(""));
        String content = "你是一个热心、可爱的智能助手，你的名字叫小贝，请以小贝的身份和语气回答问题。请根据课程库内容（课程名：课程内容）："
                + context + "来回答用户的问题。（如果用户的问题涉及到课程库内容的课程，" +
                "给用户推荐一门课程，并提示用户可以在课程页面搜索这个课程名，如果没有涉及到课程库内容的课程就不推荐，正常回答，不用提示用户。）";

        return chatClient.prompt()
                .system(s -> s.text(content)) // 动态系统消息（不会存入Redis）
                .user(prompt)
                .advisors(advisorSpec -> advisorSpec.param(ChatMemory.CONVERSATION_ID, chatId))
                .call()
                .content();

    }
    //流式聊天
//    @RequestMapping(value = "/chat",produces = "text/html;charset=utf-8")
//    public Flux<String> chat(@RequestParam("prompt") String prompt, @RequestParam("chatId") String chatId){
//        return chatClient
//                .prompt()
//                .user(prompt)
//                .advisors(advisorSpec -> advisorSpec.param(ChatMemory.CONVERSATION_ID, chatId))
//                .stream()
//                .content();
//    }

    //获取聊天记录
    @RequestMapping("/chatList")
    public List<Message> chatList(@RequestParam("chatId") String chatId){
        return redisChatMemory.get(chatId);
    }

    //清空聊天记录,开启新聊天
    @RequestMapping("/newChat")
    public void newChat(@RequestParam("chatId") String chatId){
        redisChatMemory.clear(chatId);
    }


}
